package com.sumainfor.pc.gmio.service.impl;
import com.sumainfor.common.util.ContextUtils;
import com.sumainfor.common.util.FieldCheckUtil;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.common.utlis.*;
import com.sumainfor.pc.gmio.dao.*;
import com.sumainfor.pc.gmio.feign.BasePcEpcFeign;
import com.sumainfor.pc.gmio.feign.BaseTenantFeign;
import com.sumainfor.pc.gmio.feign.ZuulFeign.ZuulFeign;
import com.sumainfor.pc.gmio.feign.extend.HouseFeign;
import com.sumainfor.pc.gmio.service.DiBillOutlayService;
import com.sumainfor.pc.gmio.service.SeBillOutlayService;
import javassist.expr.NewArray;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.omg.CORBA.OBJ_ADAPTER;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.management.relation.Relation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 租后主管查询支出账单
 */
@Service
public class DiBillOutlaySerivceImpl implements DiBillOutlayService {

    private ReentrantLock lock = new ReentrantLock(false);

    Logger log= LoggerFactory.getLogger(DiBillOutlaySerivceImpl.class);

    @Autowired
    private DiBillOutlayMapper diBillOutlayMapper;

    @Autowired
    HouseFeign HouseFeign;

    @Autowired
    ZuulFeign ZuulFeign;

    @Autowired
    BasePcEpcFeign BasePcEpcFeign;

    @Autowired
    BaseTenantFeign BaseTenantFeign;

    @Autowired
    SeWaterMeterMapper SeWaterMeterMapper;

    @Autowired
    SeEleMeterMapper SeEleMeterMapper;

    @Autowired
    SeGasMeterMapper SeGasMeterMapper;

    /**
     * 服务秘书查询业主水电燃账单列表
     */
    @Override
    public JsonResult getDiBillOutlayList(Map<String,Object> params, Pager pager){

        pager.setPageno(Integer.parseInt(params.get("pageno").toString()));
        pager.setPagesize(Integer.parseInt(params.get("pagesize").toString()));
        JsonResult result=new JsonResult();
        pager.setPagerNecessary(params, pager);
        PageUtils pageUtils = new PageUtils();

        //只有水电燃账单才根据水电燃去查询相对应的水电燃
        if(FieldCheckUtil.isMapFieldNotNull(params,new String[]{"utilityFeeRadio2"})){
            //如果水电燃查询，是全部，就清空，相对应查询全部
            if(params.get("utilityFeeRadio2").toString().equals("0")){
                params.put("utilityFeeRadio2",null);
            }
            //如果不是水电燃类型。就清空水电燃字段
            if(!params.get("BiOutType").toString().equals("4")){
                params.put("utilityFeeRadio2",null);
            }
        }


                List<String> RelationList =  new ArrayList<>();
        if (MapUtils.getInteger(params,"BiOutType")==1){
            if (MapUtils.getString(params,"ZhangDanTime")!=null&&!MapUtils.getString(params,"ZhangDanTime").equals("")){
                List<Map<String,Object>> ZhangDanTimeList = HouseFeign.getOwDelListZTime(params);
                if (ZhangDanTimeList.size()>0&&ZhangDanTimeList!=null){
                    for (Map<String,Object> mapOne:ZhangDanTimeList){
                        RelationList.add(mapOne.get("Relation").toString());
                    }
                }
            }

        }

        if (RelationList.size()>0){
            params.put("RelationList",RelationList);
        }

       List<Map<String,Object>>getDiBillOutlayList=diBillOutlayMapper.getDiBillOutlayList(params);
        Integer count = this.getDiBillOutlayListCount(params);








        if(getDiBillOutlayList.size()>0){
            String BiOutType=params.get("BiOutType").toString();
            List<String>ids;
            //获取公司。类型为1
            Integer type=1;
            switch (BiOutType){
                case "1"://业主，查询市场部业主合同
                    List<Map<String,Object>> getOwnerDealList=HouseFeign.getOwnerDealList();
                    //合并
                    getDiBillOutlayList= ListMapMergeUtil.ListMergeUtils(getDiBillOutlayList,getOwnerDealList,"Relation");
                    for (Map<String,Object> map:getDiBillOutlayList){
                        String CreateType=map.get("CreateType").toString();
                        //账单创建人类型
                        if(CreateType=="2"||CreateType.equals("2")){
                            ids=new ArrayList<String>();
                            ids.add(map.get("Create").toString());
                            JsonResult jsonResult=ZuulFeign.getUserInfo(ids);
                            if (jsonResult.isSuccess()){
                                List<Map<String, Object>>getUserInfo=(List<Map<String, Object>>)jsonResult.getResult();
                                map.putAll(getUserInfo.get(0));
                            }
                        }
                        //根据支付公司编号获取公司资料
                       // if(StringUtils.isNotEmpty(map.get("CorId").toString())){
                        if(StringUtils.isNotEmpty(MapUtils.getString(map,"CorId"))){
                            //获取当前支付的公司资料
                            Map<String,Object>getDataByTypeAndId=ZuulFeign.getDataByTypeAndId(map.get("CorId").toString(),type);
                            map.putAll(getDataByTypeAndId);
                        }
                        //支付完成的查询
                        if(FieldCheckUtil.isMapFieldNotNull(map,new String[]{"UploadUserId"})){
                            ids=new ArrayList<String>();
                            ids.add(map.get("UploadUserId").toString());
                            JsonResult jsonResult=ZuulFeign.getUserInfo(ids);
                            if (jsonResult.isSuccess()){
                                List<Map<String, Object>>getUserInfo=(List<Map<String, Object>>)jsonResult.getResult();
                                map.put("UploadUserName",getUserInfo.get(0).get("username"));
                            }
                        }

                    }







                    break;
                case "2"://供应商,查询工程部供应商
                    List<Map<String,Object>>getSupplierList=BasePcEpcFeign.getStatementSupplierList();
                    System.out.println("getSupplierList"+getSupplierList);

                    //合并
                    getDiBillOutlayList= ListMapMergeUtil.ListMergeUtils(getDiBillOutlayList,getSupplierList,"Relation");
                    System.out.println("getDiBillOutlayList"+getDiBillOutlayList);
                    for (Map<String,Object> map:getDiBillOutlayList){
                        String CreateType=map.get("CreateType").toString();
                        //账单创建人类型
                        if(CreateType=="2"||CreateType.equals("2")){
                            ids=new ArrayList<String>();
//                            ids.add(map.get("Create").toString());
//                            JsonResult jsonResult=ZuulFeign.getUserInfo(ids);
//                            if (jsonResult.isSuccess()){
//                                List<Map<String, Object>>getUserInfo=(List<Map<String, Object>>)jsonResult.getResult();
//                                map.putAll(getUserInfo.get(0));
//                            }
//                            ids.clear();
                            ids.add(map.get("Applicant").toString());
                            JsonResult jsonResult1 = ZuulFeign.getUserInfo(ids);
                            if (jsonResult1.isSuccess()){
                                List<Map<String, Object>>getUserInfo1=(List<Map<String, Object>>)jsonResult1.getResult();
                                map.putAll(getUserInfo1.get(0));
                            }
                        }

                        System.out.println("map"+map);
                        //根据支付公司编号获取公司资料
                       // if(StringUtils.isNotEmpty(map.get("CorId").toString())){
                        if(StringUtils.isNotEmpty(MapUtils.getString(map,"CorId"))){
                            //获取当前支付的公司资料
                            Map<String,Object>getDataByTypeAndId=ZuulFeign.getDataByTypeAndId(map.get("CorId").toString(),type);
                            map.putAll(getDataByTypeAndId);
                        }
                            //支付完成的查询
                            if (FieldCheckUtil.isMapFieldNotNull(map, new String[]{"UploadUserId"})) {
                                ids = new ArrayList<String>();
                                ids.add(map.get("UploadUserId").toString());
                                JsonResult jsonResult = ZuulFeign.getUserInfo(ids);
                                if (jsonResult.isSuccess()) {
                                    List<Map<String, Object>> getUserInfo = (List<Map<String, Object>>) jsonResult.getResult();
                                    map.put("UploadUserName", getUserInfo.get(0).get("username"));
                                }
                            }

                    }

                    break;
                case "3"://退租账单,查询运营部退租账单
                    List<Map<String,Object>> getAllHousingLists=HouseFeign.getAllHousingLists();
                    //合并
                    getDiBillOutlayList= ListMapMergeUtil.ListMergeUtils(getDiBillOutlayList,getAllHousingLists,"HouInfoId");
                    JsonResult jsonResult=BaseTenantFeign.getTenantList();
                    if(jsonResult.isSuccess()){
                        List<Map<String,Object>>getTenantList=(List<Map<String,Object>>)jsonResult.getResult();
                        //合并
                        getDiBillOutlayList= ListMapMergeUtil.ListMergeUtils(getDiBillOutlayList,getTenantList,"TenId");
                    }
                    for (Map<String,Object> map:getDiBillOutlayList){
                        String CreateType=map.get("CreateType").toString();
                        //账单创建人类型
                        if(CreateType=="2"||CreateType.equals("2")){
                            ids=new ArrayList<String>();
                            ids.add(map.get("Create").toString());
                            JsonResult jsonResult1=ZuulFeign.getUserInfo(ids);
                            if (jsonResult1.isSuccess()){
                                List<Map<String, Object>>getUserInfo=(List<Map<String, Object>>)jsonResult1.getResult();
                                map.putAll(getUserInfo.get(0));
                            }
                        }
                        //根据支付公司编号获取公司资料
                       // if(StringUtils.isNotEmpty(map.get("CorId").toString())){
                        if(StringUtils.isNotEmpty(MapUtils.getString(map,"CorId"))){
                            //获取当前支付的公司资料
                            Map<String,Object>getDataByTypeAndId=ZuulFeign.getDataByTypeAndId(map.get("CorId").toString(),type);
                            map.putAll(getDataByTypeAndId);
                        }
                        //支付完成的查询
                        if(FieldCheckUtil.isMapFieldNotNull(map,new String[]{"UploadUserId"})){
                            ids=new ArrayList<String>();
                            ids.add(map.get("UploadUserId").toString());
                            JsonResult jsonResult2=ZuulFeign.getUserInfo(ids);
                            if (jsonResult2.isSuccess()){
                                List<Map<String, Object>>getUserInfo=(List<Map<String, Object>>)jsonResult2.getResult();
                                map.put("UploadUserName",getUserInfo.get(0).get("username"));
                            }
                        }
                    }

                    break;
                case "4"://公共事业费,查询抄表
                    for (Map<String,Object> map:getDiBillOutlayList){
                        String CreateType=map.get("CreateType").toString();
                        //账单创建人类型
                        if(CreateType=="2"||CreateType.equals("2")){
                            ids=new ArrayList<String>();
                            ids.add(map.get("Create").toString());
                            JsonResult jsonResult1=ZuulFeign.getUserInfo(ids);
                            if (jsonResult1.isSuccess()){
                                List<Map<String, Object>>getUserInfo=(List<Map<String, Object>>)jsonResult1.getResult();
                                map.putAll(getUserInfo.get(0));
                            }
                        }
                        //根据支付公司编号获取公司资料
                       // if(StringUtils.isNotEmpty(map.get("CorId").toString())){
                        if(StringUtils.isNotEmpty(MapUtils.getString(map,"CorId"))){
                            //获取当前支付的公司资料
                            Map<String,Object>getDataByTypeAndId=ZuulFeign.getDataByTypeAndId(map.get("CorId").toString(),type);
                            map.putAll(getDataByTypeAndId);
                        }
                        //公共事业费的费用类型   1.水费  2.电费  3.燃气
                        //只有账单类型为4才有
                        String PubType=map.get("PubType").toString();
                        //账单编号
                        String Relation=map.get("Relation").toString();
                        if(StringUtils.isNotEmpty(PubType)){
                            switch (PubType){
                                case "1":
                                    //获取水费记录
                                    Map<String,Object>getWaterMeterByWameIdMap=SeWaterMeterMapper.getWaterMeterByWameIdMap(Relation);
                                    map.putAll(getWaterMeterByWameIdMap);
                                    break;
                                case "2":
                                    //获取水费记录
                                    Map<String,Object>getEleMeterByElemeIdMap=SeEleMeterMapper.getEleMeterByElemeIdMap(Relation);
                                    map.putAll(getEleMeterByElemeIdMap);
                                    break;
                                case "3":
                                    //获取水费记录
                                    Map<String,Object>getGasMeterByGasmeIdMap=SeGasMeterMapper.getGasMeterByGasmeIdMap(Relation);
                                    map.putAll(getGasMeterByGasmeIdMap);
                                    break;
                            }
                        }
                        //支付完成的查询
                        if(FieldCheckUtil.isMapFieldNotNull(map,new String[]{"UploadUserId"})){
                            ids=new ArrayList<String>();
                            ids.add(map.get("UploadUserId").toString());
                            JsonResult jsonResult2=ZuulFeign.getUserInfo(ids);
                            if (jsonResult2.isSuccess()){
                                List<Map<String, Object>>getUserInfo=(List<Map<String, Object>>)jsonResult2.getResult();
                                map.put("UploadUserName",getUserInfo.get(0).get("username"));
                            }
                        }
                    }
                    List<Map<String,Object>>HousingLists=HouseFeign.getAllHousingLists();
                    //合并
                    getDiBillOutlayList= ListMapMergeUtil.ListMergeUtils(getDiBillOutlayList,HousingLists,"HouInfoId");

                    break;
            }
        }
        if (count==0){
            return pageUtils.getJsonResult(new ArrayList<Map<String,Object>>(), params,count);
        } else{
            return pageUtils.getJsonResult(getDiBillOutlayList, params, count);
        }


       // return getDiBillOutlayList;



    }
    /**
     * 服务秘书查询业主水电燃账单列表总数
     */
    @Override
    public Integer getDiBillOutlayListCount(Map<String,Object> params){

        return diBillOutlayMapper.getDiBillOutlayListCount(params);
    }
    /**
     * 租后主管查询日账核对列表
     */
    @Override
    public List<Map<String, Object>> getDiBillOutlCheckList(Map<String, Object> params) {
        return diBillOutlayMapper.getDiBillOutlCheckList(params);
    }
    /**
     * 租后主管查询日账核对列表总数
     */
    @Override
    public Integer getDiBillOutlCheckListCount(Map<String, Object> params) {
        return diBillOutlayMapper.getDiBillOutlCheckListCount(params);
    }

    /**
     * 功能描述:
     * 财务打款
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/7/4 20:57
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean UpdateDiBillOulPay(Map<String,Object>params){
        boolean result=false;
        //修改处理
        try {
            Map<String, Object> commonUpdateParms = new HashMap<String, Object>();
            commonUpdateParms.put("by", ContextUtils.getUserId());//操作人
            commonUpdateParms.put("term", "2");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
            commonUpdateParms.put("fnc",
                    this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
            ParamsCommon.commonUpdateParms(commonUpdateParms);
            params.putAll(commonUpdateParms);
            params.put("UploadUserId",ContextUtils.getUserId());
            params.put("PayTime", ConvertDateTime.getCurrentTime());
            params.put("Status", 2);//账单状态 1.待支付 2.支付完成  3已废弃（业主违约）
            diBillOutlayMapper.UpdateDiBillOulPay(params);
            result=true;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

        return result;
    }
}
